function [encodedBits, alpha]=WiSiL_Encoder_pccc( bitsTx, encoder )
% WISIL_ENCODER_PCCC Parallel concatenated convolutional codes.
%
%  [ ENCODEDBITS, ALPHA ] = WiSiL_Encoder_pccc( BITSTX, ENCODER )
%  implements the turbo encoder scheme defined by 3GPP 36.212 V8.2.0 on the 
%  data bits BITSTX, with coding parameters given in ENCODER. The encoded
%  bits are returned in ENCODEDBITS and alpha contains the index of the
%  interleaved bits, to be used by the deinterleaver.

% History:
% Rafhael Medeiros de Amorim ( rma.petit@gmail.com ),30/Jul/2008
%   created
% Andre Noll Barreto, 18/Abr/2011
%   included code termination in this function




WiSiL_Encoder_interleaverTable;
% Interleaver table (36.212) - Used to calculate the interleaved sequence
% to the second convolutiona encoder.

Ki = length(bitsTx);   % Ki index - See 36.212 for more information.
index = find (K == Ki); % Find Ki at interleaver table

%-- Dealing with null values. --
auxiliar = isnan(bitsTx);
temp = find(auxiliar == 1);
bitsTx(temp) = 0;
%--         ---               --

%-- Interleaved Sequence      --
alpha(1,:) = mod((1:Ki)*f1(index)+(1:Ki).^2*f2(index),Ki);
alpha(1,:) = alpha+1;
%--         ---               --

% Set Encoder Parameters
constraint = 4; %Constraint length
feedback = encoder.TurboCoding.feedback;  %Feedback polynomial
poly = encoder.TurboCoding.poly;          %Generator polynomials
trellis = poly2trellis(constraint,poly,feedback); % Trellis

% Initialization of matrices
encodedBits = zeros(3, length(bitsTx) );

%First convolutional encoder.
[auxiliar, state(1)] = convenc(bitsTx,trellis); 
%Second convolutional encoder.
[auxiliar2, state(2)] = convenc(bitsTx(alpha),trellis); 
encoded(1,:) = auxiliar(1:2:end); % Systematic output.
encoded(2,:) = auxiliar(2:2:end); % Parity output (1st encoder)
encoded(3,:) = auxiliar2(2:2:end); %Parity output (2nd encoder)

encoded(:,temp) = []; %Eliminating null values.

% Trellis Termination
poly = [03 15];
tail = [0 0 0];

trellis = poly2trellis(constraint,poly);

auxiliar = [];
auxiliar(1,:) = convenc(tail,trellis,state(1));
auxiliar(2,:) = convenc(tail,trellis,state(2));

tailbits = [auxiliar(1,:) auxiliar(2,:)];
tailbits=reshape(tailbits,3,[]);

encodedBits = [encoded, tailbits];
